package com.ysh.webflux.controller;

import com.ysh.webflux.pojo.User;
import com.ysh.webflux.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 袁胜虎 on 2022/9/22 17:15
 */
@RestController
public class TestController {


    private UserService userService;


    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/user/info/{id}")
    public Mono<User> findById(@PathVariable int id) {
        return userService.getUserById(id);
    }

    @GetMapping("/users")
    public Flux<User> findAllUsers() {
        return userService.getAllUser();
    }

    @PostMapping("/user")
    public Mono<Void> addUser(@RequestBody Mono<User> user) {
        // return userService.saveUserInfo(Mono.just(user));
        return userService.saveUserInfo(user);
    }

    /**
     * produces 可以设置响应结果的类型
     * @return
     */
    @GetMapping(value ="/users/stream",produces= MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<User> getUsersStream() {
        return userService.getUsersStream();
    }



    @GetMapping("/user/info1/{id}")
    public Mono<User> findById2(@PathVariable int id) {
        User user = userService.getUserById1(id);
        return Mono.just(user);
    }

    @GetMapping("/users1")
    public Flux<User> findAllUsers2() {
        List<User> userList = userService.getAllUser1();
        return Flux.fromIterable(userList);
    }

    @PostMapping("/user1")
    public Mono<Void> addUser2(@RequestBody User user) {
        // return userService.saveUserInfo(Mono.just(user));
        userService.saveUserInfo1(user);
        return Mono.empty();
    }
}
